package com.example.asm_pro

import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes


class MyClassVisitor(classVisitor: ClassVisitor?) : ClassVisitor(Opcodes.ASM9, classVisitor) {
    override fun visitMethod(
        access: Int,
        name: String?,
        descriptor: String?,
        signature: String?,
        exceptions: Array<out String>?
    ): MethodVisitor {
        val mv = super.visitMethod(access, name, descriptor, signature, exceptions)
        println("MyGradlePlugin visitMethod $name")
        println("MyGradlePlugin name === \"onCreate\": ${name === "onCreate"}")
        return if (name.equals("onCreate")) {
            println("MyGradlePlugin MyMethodVisitor $name")
            MyMethodVisitor(mv)
        } else {
            mv
        }
    }

    internal inner class MyMethodVisitor(methodVisitor: MethodVisitor?) :
        MethodVisitor(Opcodes.ASM7, methodVisitor) {
        override fun visitCode() {
            super.visitCode()
            // 插入 Log.d("TAG", "onCreate 被调用")
            mv.visitLdcInsn("TAG"); // 第一个参数：日志标签
            mv.visitLdcInsn("onCreate 被调用"); // 第二个参数：日志内容
            mv.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                "android/util/Log",
                "d",
                "(Ljava/lang/String;Ljava/lang/String;)I",
                false
            );

            // 解决堆栈不平衡问题，丢弃 Log.d 返回值（I）
            mv.visitInsn(Opcodes.POP);
        }
    }
}